package ynu.edu.ky_elm_springboot3.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import ynu.edu.ky_elm_springboot3.mapper.UserMapper;
import ynu.edu.ky_elm_springboot3.po.User;
import ynu.edu.ky_elm_springboot3.service.UserService;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public int getUserById(String userId) {
        return userMapper.getUserById(userId);
    }

    @Override
    public int saveUser(User user) {
        log.info("Saving user: {}", user);
        return userMapper.saveUser(user);
    }

    @Override
    public User findByUserId(String userId) {
        return userMapper.findByUserId(userId);
    }

    @Override
    public User login(String userId, String password) {
        log.info("Attempting login for userId: {}", userId);
        User user = userMapper.findByUserId(userId);
        log.info("Found user: {}", user);
        
        if (user != null) {
            log.info("Comparing passwords - Input: {}, Stored: {}", password, user.getPassword());
            boolean matches = passwordEncoder.matches(password, user.getPassword());
            log.info("Password match result: {}", matches);
            if (matches) {
                return user;
            }
        }
        return null;
    }
} 